<?php
namespace App\Admin\Controllers\FileModel;
use App\Http\Controllers\Controller;
use Dcat\Admin\FormStep\Form as StepForm;
use App\Models\InputStepForm;
use App\Models\InformationList;
use Dcat\Admin\Form;
use Dcat\Admin\Admin;
use Dcat\Admin\Layout\Content;
use Illuminate\Http\Request;
use PhpOffice\PhpWord\TemplateProcessor;
use PhpOffice\PhpWord\PhpWord;
use Dcat\Admin\Grid;
use Illuminate\Support\Facades\DB;
use Log;
use Dcat\Admin\Widgets\Alert;
// use Dcat\Admin\Widgets\Form;
class SchemeController extends Controller
{
    //换班表
    protected $options = [
        1 => '显示文本框',
        2 => '显示编辑器',
        3 => '显示文件上传',
        4 => '还是显示文本框',
    ];
    // use PreviewCode;
    public function index(Content $content)
    {
        return $content
            // ->body('<div style="margin:5px 0 15px;">'.$step->buildPreviewButton().'</div>')
            ->body($this->form())
            ->header('电除尘器节能减排改造方案建议书')
            ->description('分步表单');
    }
    protected function form()
{
    Admin::js('/stepform/js/jquery.smartWizard.min.js');
    Admin::css('/stepform/css/step.css');
    return Form::make(new InputStepForm(), function (Form $form) {
            $form->title('电除尘器节能减排改造方案建议书');
            $form->action('Schemestep');
            $form->disableListButton();
            $form->multipleSteps()
                ->remember() 
                ->width('100%')
                ->add('项目信息', function (StepForm $step) use ($form) {
                    $info = '<i class="fa fa-exclamation-circle"></i>机头电除尘器设计参数';
                    $step->html(Alert::make($info)->info());
                    $step->text('projectName',trans('项目名称'))->required();
                    $step->text('a3f',trans('室数'))->required();
                    $step->text('a3g',trans('电场数量'))->required();
                    $step->text('a3n',trans('断面积(m²)'))->required();
                    $step->text('a3t',trans('同极间距'))->required();
                    $step->text('a3h',trans('电场有效高度(m),单位为：m'))->required()->help('<i style="color:red">注意：单位为m</i>');
                    $step->text('a3q',trans('电场有效长度(m),单位为：m'))->required()->help('<i style="color:red">注意：单位为m</i>');
                    $step->text('a3r',trans('阳极排数(排)'))->required();
                    $step->text('a3s',trans('阴极排数(排)'))->required();
                    $step->text('a3u',trans('有效收尘面积(m²)'));
                    $step->text('a3v',trans('比积尘面积(m²/m³/s)'));
                    $step->text('a3o',trans('流速(s/m)'));
                    $step->text('a2b',trans('比电阻（Ω·cm）'))->required();
                    $step->text('a3b',trans('入口粉尘浓度(g/Nm3)'))->required();
                    $step->text('a3d',trans('目前排放浓度(mg/m3)'))->required();
                    $step->text('a1f',trans('入口烟气量(m³/h)'))->required();
                    $step->text('a1g',trans('烟气温度(℃)'))->required();
                    $a3w = [
                        'C480' => 'C480',
                        'BE' => 'BE',
                        'C390' => 'C390',
                        'C818' => 'C818',
                        'ZT24' => 'ZT24',
                        '其他' => '其他',
                    ];
                    $step->select('a3w',trans('阳极板形式、数量'))->options($a3w);
                    $a3x = [
                        '芒刺线' => '芒刺线',
                        '针刺线' => '针刺线',
                        'V15线' => 'V15线' ,
                        '螺旋线' => '螺旋线' ,
                        '其他' => '其他' ,
                    ];
                    $step->select('a3x',trans('阴极线形式、数量'))->options($a3x);
                    $a3p = [
                        '单相工频电源'=>'单相工频电源',
                        '三相工频电源'=>'三相工频电源',
                        '高频电源'=>'高频电源',
                        '高频脉冲'=>'高频脉冲',
                        '变频脉冲电源'=>'变频脉冲电源',
                        '恒流源'=>'恒流源'
                    ];
                    $step->select('a3p',trans('电场电源类型'))->options($a3p);
                    $info = '<i class="fa fa-exclamation-circle"></i>目前机头电除尘器运行参数';
                    $step->html(Alert::make($info)->info());
                    $step->table('a4a', trans('各个电场'),function ($table) {
                        $table->text('name','电场名称')->required();
                        $table->text('dianya1','一次电压(V)')->required();
                        $table->text('dianliu1','一次电流(A)')->required();
                        $table->text('dianya2','二次电压(kV)')->required();
                        // $table->text('采样电阻');
                        $table->text('dianliu2','二次电流(mA)')->required();
                        // $table->text('I2反馈直流电压(V)');
                        // $table->text('U2反馈直流电压(V)');
                    })->rules('required');
                    $step->text('a4b',trans('其他补充'))->placeholder('请输入电源厂家和规格');
                });
        });
    }

    public function step(Request $request){
        $info = $request->all();
        if(empty($info['CURRENT_VALIDATION_STEP'])&&$info['ALL_STEPS']==1){//提交
            Log::info($info);
            //实例化 phpword 类
            $PHPWord = new PhpWord();
            //指定事先制作好的模板文件路径
            $templateProcessor = new TemplateProcessor(public_path("filemodel/demo111.docx"));
           
            //判断参数
            if($info['a3o'] > 0.9){
                $b['fengsu'] = '过高';
            }else{
                $b['fengsu'] = '正常';
            }
            if(($info['a3v'] < 80)||(!isset($info['a3v']))){
                $b['bijichen'] = '偏低';
            }else{
                $b['bijichen'] = '正常';
            }

            //转换key
            $a4a=[];
            if(isset($info['a4a'])){
            foreach ($info['a4a'] as $k => $v) {
                $a4a[] = $v;
            }
            // print_r($a4a);die;
            $rows=count($a4a);//总行数
            $templateProcessor->cloneRow('number',$rows);//复制行
                for($i=0;$i<$rows;$i++){
                    $templateProcessor->setValue("number#".($i+1),$a4a[$i]['name']);//替换变量
                    $templateProcessor->setValue("一次电压(V)#".($i+1),$a4a[$i]['dianya1']);//替换变量
                    $templateProcessor->setValue("一次电流(A)#".($i+1),$a4a[$i]['dianliu1']);
                    $templateProcessor->setValue("二次电压(kV)#".($i+1),$a4a[$i]['dianya2']);
                    $templateProcessor->setValue("二次电流(mA)#".($i+1),$a4a[$i]['dianliu2']);
                    $a4a[$i]['输出功率'] = number_format($a4a[$i]['dianya2']*$a4a[$i]['dianliu2']/1000,2);
                    $a4a[$i]['输入功率'] = number_format($a4a[$i]['dianya1']*$a4a[$i]['dianliu1']/1000,2);
                    $a4a[$i]['转换效率'] = number_format($a4a[$i]['输出功率']/$a4a[$i]['输入功率'],4)*100;
        
                    $templateProcessor->setValue('输出功率#'.($i+1), $a4a[$i]['输出功率']);
                    $templateProcessor->setValue('输入功率#'.($i+1), $a4a[$i]['输入功率']);
                    $templateProcessor->setValue('转换效率#'.($i+1), $a4a[$i]['转换效率']);
                }
            }else{
                $templateProcessor->setValue("number",'');//替换变量
                $templateProcessor->setValue("一次电压(V)",'');//替换变量
                $templateProcessor->setValue("一次电流(A)",'');
                $templateProcessor->setValue("二次电压(kV)",'');
                $templateProcessor->setValue("二次电流(mA)",'');
                $templateProcessor->setValue('输出功率','');
                $templateProcessor->setValue('输入功率','');
                $templateProcessor->setValue('转换效率','');
            }
        
            $templateProcessor->setValue('projectName',$info['projectName']);
            $templateProcessor->setValue('yearmonth',date('Y-m-d H:i:s'));
            $templateProcessor->setValue('a3f',$info['a3f']);
            $templateProcessor->setValue('a3g',$info['a3g']);
            $templateProcessor->setValue('a3p',$info['a3p']);
            $templateProcessor->setValue('a3d',$info['a3d']);
            $templateProcessor->setValue('a4b',$info['a4b']);
            $templateProcessor->setValue('a3n',$info['a3n']);
            $templateProcessor->setValue('a3t',$info['a3t']);
            $templateProcessor->setValue('a3w',$info['a3w']);
            $templateProcessor->setValue('a3x',$info['a3x']);
            $templateProcessor->setValue('a3q',$info['a3q']);
            $templateProcessor->setValue('a3h',$info['a3h']);
            $templateProcessor->setValue('a3s',$info['a3s']);
            $templateProcessor->setValue('a3r',$info['a3r']);
            $templateProcessor->setValue('a3u',$info['a3u']);
            $templateProcessor->setValue('a3v',$info['a3v']);
            $templateProcessor->setValue('a3o',$info['a3o']);
            $templateProcessor->setValue('a2b',$info['a2b']);
            $templateProcessor->setValue('a3b',$info['a3b']);
            $templateProcessor->setValue('a1f',$info['a1f']);
            $templateProcessor->setValue('a1g',$info['a1g']);

            
            unset($info['_file_']);
            unset($info['CURRENT_VALIDATION_STEP']);
            unset($info['ALL_STEPS']);
            unset($info['_token']);
            $data['admin_id'] = Admin::user()->id;
            $data['name'] = $info['projectName'].'电除尘器节能减排改造方案建议书'.date('Y-m-d H:i');
            $data['data'] = $info;
            // $data['content'] = json_encode($info);
            // $insertData['content'] = json_encode($data);
            $insertData['name'] = $data['name'];
            $insertData['type'] = 13;
            $insertData['admin_id'] = Admin::user()->id;
            $insertData['created_at'] = date('Y-m-d H:i:s');
            // $templateProcessor->saveAs(public_path('filemodellist/'.$info['projectname'].md5(time()) . ".docx"));
            $templateProcessor->saveAs(public_path('filemodellist/'.$data['name'].".docx"));
            InformationList::insert($insertData);
            return $this->form()->saving(function (Form $form) {
                // 清空缓存
                $form->multipleSteps()->flushStash();
                // 拦截保存操作
                return response(
                    $form->multipleSteps()
                        ->done()
                        ->render()
                );
            })->store();
        }
    }

    /**
     * 保存
     *
     * @return \Symfony\Component\HttpFoundation\Response
     */
    public function store(Request $requset)
    {
        return $this->form()->saving(function (Form $form) {
            
            // 清空缓存
            $form->multipleSteps()->flushStash();
            // 拦截保存操作
            return response(
                $form->multipleSteps()
                    ->done()
                    ->render()
            );
        })->store();
    }

    public function list($id,Content $content){
        return $content
            ->header('表格列表')
            ->description()
            ->body($this->grid($id));
    }
    protected function grid($typeid)
    {
        return new Grid(InformationList::where(['admin_id'=>Admin::user()->id,'type'=>$typeid]), function (Grid $grid) {
            $grid->showActions();
            $grid->disableDeleteButton();
            $grid->disableQuickEditButton();
            $grid->disableViewButton();
            $grid->disableCreateButton();
            $grid->disableEditButton();
            $grid->fixColumns(2);
            
            $grid->column('id', 'ID');
            $grid->column('name', '名称');
            $grid->column('type','类型')->display(function($type) {
                return Db::table('xfy_info_model')->where(['id'=>$type])->value('name');
            });
            $grid->actions(function (Grid\Displayers\Actions $actions) {
                $id = $actions->getKey();
                $edit_url = admin_base_path('downloadfile/'.$id);
                $actions->append("<a href='$edit_url'>下载</a>");
            });
        });
    }
}